package com.lf.plugin.lf125_Plugin;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.pl.serialport.SerialPort;
import com.znht.iodev2.PowerCtl;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class LF125TagThread {
    private String path = "/dev/ttysWK2";
    private int rate = 9600;
    private PowerCtl powerCtl;
    private SerialPort mSerial;
    private InputStream mInputStream;
    private OutputStream mOutputStream;
    private Handler handler;
    private Thread readThread;
    private volatile boolean isReading = false;
    private final Object lock = new Object();

    public static final int MSG_RESULT = 1101;

    public void setPath(String path) {
        this.path = path;
    }

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    // 初始化线程
    public void init() {
        Log.e("LF134KTag", "init");
        powerCtl = new PowerCtl();
        powerCtl.identity_uhf_power(1);
        powerCtl.identity_ctl(1);
        powerCtl.uhf_ctl(1);
        try {
            mSerial = new SerialPort(path, rate, 0);
            mInputStream = mSerial.getInputStream();
            mOutputStream = mSerial.getOutputStream();
            Thread.sleep(500);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void startRead() {
        synchronized (lock) {
            if (isReading) return;

            isReading = true;
            readThread = new Thread(new ReadRunnable());
            readThread.start();
        }
    }

    public void stopRead() {
        synchronized (lock) {
            isReading = false;
            if (readThread != null) {
                try {
                    readThread.interrupt();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    readThread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private class ReadRunnable implements Runnable {
        @Override
        public void run() {
            try {
                byte[] buffer = new byte[256];
                while (isReading && !Thread.currentThread().isInterrupted()) {
                    int size = mInputStream == null ? 0 : mInputStream.read(buffer);
                    if (size > 0) {
                        Log.e("LF125KTag", Tools.Bytes2HexString(buffer, size));
                        getID(buffer, size);
                    }
                }
            } catch (IOException e) {
                if (isReading) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void getID(byte[] buff, int size) {
        if (buff[0] != 0x02 || buff[size - 1] != 0x03 || size < 10) {
            return;
        }

        byte[] idBuff = new byte[8];
        byte[] user = new byte[2];
        System.arraycopy(buff, 3, idBuff, 0, 8);
        System.arraycopy(buff, 1, user, 0, 2);

        String idStr = new String(idBuff);
        long id = Long.parseLong(idStr, 16);

        String countryStr = "0" + new String(user);
        int countryInt = Integer.parseInt(countryStr, 16);

        if (handler != null && isReading) {
            Message msg = new Message();
            msg.what = MSG_RESULT;
            Bundle b = new Bundle();
            b.putLong("id", id);
            b.putInt("user", countryInt);
            msg.setData(b);
            handler.sendMessage(msg);
        }

        Log.d("LF125KTag", "ID: " + idStr + ", Parsed ID: " + id + ", Country: " + countryStr + ", Parsed Country: " + countryInt);
    }

    public void close() {
        stopRead();
        if (mSerial != null) {
            mSerial.close();
        }
        if (powerCtl != null) {
            powerCtl.identity_uhf_power(0);
            powerCtl.identity_ctl(0);
            powerCtl.uhf_ctl(0);
        }
    }
}
